import subprocess
import logging
import os
import sys

log = logging.getLogger(__name__)
basedir = os.path.dirname(os.path.abspath(__file__))

formatter = logging.basicConfig(
    filename='{basedir}/crm_recovery.log'.format(basedir=basedir),
    level=logging.DEBUG,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%a, %d %b %Y %H:%M:%S')


def run_cmd(cmd, information=None, file_output=None):
    """
    执行命令并发送初始信息给mq
    :param cmd: 执行的备份命令
    :param information: 备份信息实例
    :param file_output: 文件输出句柄
    :return:
    """
    log.info(cmd)
    if file_output is None:
        stdout = subprocess.PIPE
        stderr = subprocess.STDOUT
    else:
        stdout = file_output
        stderr = file_output
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=stdout,
                         stderr=stderr)
    pid = p.pid
    try:
        information.set_pid_info(pid=pid)
        information.backup_startup_publish()
    except AttributeError as e:
        pass
    # result = p.stdout.read()d
    return_code = p.wait()
    # print(type(p.stdout))
    # print(p.stdout)
    return p


def main():
    p = run_cmd("crm status")
    detect_failure_flag = 0
    for line in p.stdout:
        # print(line.decode('utf-8'))
        line_string = line.decode('utf-8')
        if line_string.startswith("Failed Actions:"):
            # if line_string == "Failed Actions:\n":
            detect_failure_flag = 1
            log.info("Detect crm status error ! Now we analyze the output and try to do the recovery")
        if detect_failure_flag == 1:
            if line_string.startswith('* '):
                log.info("crm status error:{}".format(line_string))
                resource_name_type = line_string.split()[1]
                resource_name = resource_name_type.split('_')[0] + '_' + resource_name_type.split('_')[1]
                run_cmd('crm resource cleanup {resource_name}'.format(resource_name=resource_name))
        else:
            pass


if __name__ == "__main__":
    sys.exit(main())
